<template>
  <div class="app-container">
    <!-- 操作条件 -->

    <div class="btnGround">
      <div>
        <el-button icon="el-icon-refresh-right" @click="ResetList">刷新</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addCampusScenery">添加校园风光</el-button>
      </div>
    </div>
    <div class="pictureList">
      <div
        v-for="(itemi, indexi) in campusSceneryList"
        :key="indexi"
        class="listItem"
      >
        <div
          style="position: relative;"
          @mouseenter="isShow = indexi"
          @mouseleave="isShow = -1"
        >
          <span v-show="isShow === indexi" v-if="$route.query.status != 1" class="shade">
            <el-tooltip class="item" effect="dark" content="放大" placement="top">
              <i class="el-icon-view" @click.stop="bosst(itemi.simgurl)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <i class="el-icon-edit" @click.stop="editCampusScenery(itemi.scenery_id,itemi.sname,itemi.simgurl,itemi.is_bg)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <i class="el-icon-delete" @click.stop="deleteCampusScenery(itemi.scenery_id)" />
            </el-tooltip>

          </span>
          <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
            <img width="100%" :src="preImg" alt>
          </el-dialog>
          <el-image :src="itemi.simgurl" />
          <div v-if="itemi.is_bg == 1" class="is_bg">当前背景图</div>
        </div>
        <div class="itemText">{{ itemi.sname }}</div>
      </div>
    </div>
    <div class="bottomPagination">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10,30,50]"
        :page-size="pageSize"
        layout=" sizes, prev, pager, next,total, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <el-dialog title="新增校园风光" :visible.sync="dialogTableVisible" width="450px" center>
      <el-form ref="form1" :model="form" :rules="rules" class="addCampusScenery">
        <el-form-item label="描述:" label-width="100" prop="sname">
          <el-input v-model="form.sname" style="width:85%" />
        </el-form-item>
        <el-form-item label="图片:" label-width="100" prop="simgurl">
          <input
            id="upload1"
            ref="clearFile1"
            type="file"
            style="display:none"
            class="add-file-right-input"
            @change="addUploadImg($event)"
          >
          <div v-if="!form.simgurl" class="uploadImg" @click="upload1">
            <i class="el-icon-plus" />
          </div>
          <div v-if="form.simgurl" class="addImage">
            <el-image :src="form.simgurl" />
            <div class="delImg" @click="delAddImage">
              <i class="el-icon-close" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="设置背景:" label-width="100">
          <el-switch v-model="form.is_bg" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑校园风光" :visible.sync="dialogTableVisible1" width="450px" center>
      <el-form ref="form2" :model="form1" :rules="rules1" class="addCampusScenery">
        <el-form-item label="描述:" label-width="100" prop="sname">
          <el-input v-model="form1.sname" style="width:85%" />
        </el-form-item>
        <el-form-item label="图片:" label-width="100" prop="simgurl">
          <input
            id="upload2"
            ref="clearFile2"
            type="file"
            style="display:none"
            class="add-file-right-input"
            @change="editUploadImg($event)"
          >
          <div v-if="!form1.simgurl" class="uploadImg" @click="upload2">
            <i class="el-icon-plus" />
          </div>
          <div v-if="form1.simgurl" class="addImage">
            <el-image :src="form1.simgurl" />
            <div class="delImg" @click="delEditImage">
              <i class="el-icon-close" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="设置背景:" label-width="100">
          <el-switch v-model="form1.is_bg" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addScenery, getScenery, editScenery, deleteScenery } from '@/api/trembleSchool/campusScenery'
import axios from 'axios'
export default {
    components: {
    },
    props: {},
    data() {
        return {
            isShow: -1,
            currentPage: 1, // 页数
            total: 0, // 总数
            pageSize: 10, // 每页条数
            dialogVisible: false, // 风光列表，遮罩层
            preImg: '',
            // 添加校园风光
            dialogTableVisible: false, // 弹出框
            form: {
                sname: '', // 描述
                simgurl: '', // 图片链接
                is_bg: false
            },
            explainImgList: [],
            rules: {
                sname: [
                    { required: true, message: '请输入风光校园描述', trigger: 'blur' }
                ],
                simgurl: [
                    { required: true, message: '请选择风光校园图片', trigger: 'change' }
                ]
            },

            // 修改校园风光
            dialogTableVisible1: false, // 弹出框
            form1: {
                sname: '', // 描述
                simgurl: '', // 图片链接
                scenery_id: '',
                is_bg: null
            },
            rules1: {
                sname: [
                    { required: true, message: '请输入风光校园描述', trigger: 'blur' }
                ],
                simgurl: [
                    { required: true, message: '请选择风光校园图片', trigger: 'change' }
                ]
            },

            campusSceneryList: [], // 校园风光列表
            imgUrl: '' // 上传图片临时路径

        }
    },
    computed: {},
    watch: {},
    beforeCreate() {
    // 生命周期钩子：组件实例刚被创建，组件属性计算之前，如 data 属性等
    },
    created() {
    // 生命周期钩子：组件实例创建完成，属性已绑定，但 DOM 还未生成，el 属性还不存在
    // 初始化渲染页面
    },
    beforeMount() {
    // 生命周期钩子：模板编译/挂载之前
    },
    mounted() {
    // 生命周期钩子：模板编译、挂载之后（此时不保证已在 document 中）
        this.getCampusScenery()
    },
    methods: {
        bosst(url) {
            this.preImg = url
            this.dialogVisible = true
        },
        addCampusScenery() {
            this.dialogTableVisible = true
        },
        editCampusScenery(scenery_id, sname, simgurl, is_bg) {
            this.dialogTableVisible1 = true
            this.form1.sname = sname
            this.form1.simgurl = simgurl
            this.form1.scenery_id = scenery_id
            if (is_bg === 1) {
                this.form1.is_bg = true
            } else {
                this.form1.is_bg = false
            }
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getCampusScenery()
        },
        handleSizeChange(val) {
            this.currentPage = 1
            this.pageSize = val
            this.getCampusScenery()
        },
        // 刷新
        ResetList() {
            this.getCampusScenery()
        },
        // 获取校园风光
        getCampusScenery() {
            var data = {
                page: this.currentPage,
                pagesize: this.pagesize
            }
            getScenery(data).then(res => {
                if (res.code === 200) {
                    this.campusSceneryList = res.data.data.reverse()
                    this.total = res.data.total
                    console.log('校园风光', this.campusSceneryList)
                }
            })
        },
        addUploadImg($e) {
            console.log('触发上传')
            if ($e.target.files[0].type.split('/')[0] != 'image') {
                this.$message.error('上传文件类型不符合')
                return false
            }
            let files = $e.target.files[0]
            console.log('files', files)
            let formData = new FormData()
            formData.append('file', files)
            let config = {
                headers: { 'Content-Type': 'multipart/form-data' }
            } // 添加请求头
            axios({
                method: 'post',
                url: 'http://api.zhizhuedu.cn/api/v1/upload',
                data: formData,
                config
            }).then(res => {
                console.log('res', res.data)
                if (res.data.code === 200 && res.data.data.fileUrl) {
                    console.log('图片路径', res.data.data.fileUrl)
                    this.form.simgurl = res.data.data.fileUrl
                    this.$refs['form1'].clearValidate('simgurl')
                    delete this.$refs['form1'].rules.simgurl
                } else {
                    this.$message.error('上传失败,请重新上传图片')
                }
            }).catch(err => {
                console.log('err', err)
            })
            this.$refs['clearFile1'].value = ''
        },
        editUploadImg($e) {
            console.log('触发上传')
            if ($e.target.files[0].type.split('/')[0] != 'image') {
                this.$message.error('上传文件类型不符合')
                return false
            }
            let files = $e.target.files[0]
            console.log('files', files)
            let formData = new FormData()
            formData.append('file', files)
            let config = {
                headers: { 'Content-Type': 'multipart/form-data' }
            } // 添加请求头
            axios({
                method: 'post',
                url: 'http://api.zhizhuedu.cn/api/v1/upload',
                data: formData,
                config
            }).then(res => {
                console.log('res', res.data)
                if (res.data.code === 200 && res.data.data.fileUrl) {
                    console.log('图片路径', res.data.data.fileUrl)
                    this.form1.simgurl = res.data.data.fileUrl
                    this.$refs['form2'].clearValidate('simgurl')
                    delete this.$refs['form2'].rules.simgurl
                } else {
                    this.$message.error('上传失败,请重新上传图片')
                }
            }).catch(err => {
                console.log('err', err)
            })
            this.$refs['clearFile2'].value = ''
        },
        upload1() {
            document.getElementById('upload1').click()
        },
        upload2() {
            document.getElementById('upload2').click()
        },
        delAddImage() {
            this.form.simgurl = ''
            this.upload1()
        },
        delEditImage() {
            this.form1.simgurl = ''
            this.upload2()
        },
        // 增加校园风光确定方法
        add() {
            this.$refs['form1'].validate((valid) => {
                if (valid) {
                    this.form.is_bg = this.form.is_bg ? 1 : 0
                    console.log('参数', this.form)
                    addScenery(this.form).then(res => {
                        if (res.code === 200) {
                            this.$notify({
                                title: '成功',
                                message: '添加成功',
                                type: 'success'
                            })
                            this.dialogTableVisible = false
                            this.form.sname = ''
                            this.form.simgurl = ''
                            this.getCampusScenery()
                        }
                    })
                } else {
                    return false
                }
            })
        },
        // 编辑校园风光确定方法
        edit() {
            this.$refs['form2'].validate((valid) => {
                if (valid) {
                    var data = {
                        scenery_id: this.form1.scenery_id,
                        sname: this.form1.sname,
                        simgurl: this.form1.simgurl,
                        is_bg: this.form1.is_bg ? 1 : 0
                    }

                    console.log('参数', data)
                    editScenery(data).then(res => {
                        if (res.code === 200) {
                            this.$notify({
                                title: '成功',
                                message: '修改成功',
                                type: 'success'
                            })
                            this.dialogTableVisible1 = false
                            this.getCampusScenery()
                        }
                    })
                } else {
                    return false
                }
            })
        },
        deleteCampusScenery(scenery_id) {
            this.$confirm('确定要删除该校园风光', '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteScenery({
                    scenery_id: scenery_id
                }).then(res => {
                    console.log('删除校园风光', res)
                    if (res.code === 200) {
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success'
                        })
                        this.getCampusScenery()
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        }

    }
}
</script>

<style lang="scss" scoped>

.btnGround {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row-reverse;
    justify-content: space-between;
    margin: 20px 0 15px 0;
}

.bottomPagination {
    padding: 15px 0;
}
.pictureList{
    display: flex;
    flex-wrap: wrap;
.listItem{
    width: 275px;
    height: 240px;
    .el-image{
        width: 240px;
        height: 180px;
        margin: 20px;
    }
    .itemText{
        text-align: center;
    }
}
}
.shade {
  width: 240px;
  height: 180px;
  position: absolute;
  top:20px;
  left:20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: rgba(48, 48, 48, 0.4);
  z-index: 1000;
  .el-icon-zoom-in {
    font-size: 20px;
    color: #ffff;
  }
  .el-icon-delete {
    font-size: 20px;
    color: #ffff;
    cursor: pointer;
  }
  .el-icon-edit{
    font-size: 20px;
    color: #ffff;
    cursor: pointer;
  }
  .el-icon-view {
    font-size: 20px;
    color: #ffff;
    cursor: pointer;
  }
}
.bottomPagination{
    text-align: center;
    margin-top: 20px;
}
.uploadImg{
     display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  width: 100px;
  height: 100px;
  color: #8c939d;
  .el-icon-plus {
  font-size: 25px;
}
}
.addImage{
    .el-image {
        width: 100px;
        height:100px ;
    }
    .delImg{
        width: 20px;
        height: 20px;
        color: white;
        background: rgb(255,114,114);
        border-radius: 50%;
        position: absolute;
        left: 143px;
        top:-10px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
.is_bg{
    position: absolute;
    bottom: 25px;
    right:18px;
    color: white;
}
</style>
